<template>
  <div class="recharge-page">
    <Header />

    <!-- 充值内容区域 -->
    <div class="recharge-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2 class="page-title">账户充值</h2>
        <p class="page-subtitle">为您的账户充值，享受更便捷的购物体验</p>
      </div>
      <div class="container">
        <div class="recharge-wrapper">
          <div class="recharge-main">
            <!-- 左侧充值表单 -->
            <div class="recharge-form-section">
              <div class="form-card">
                <!-- 当前余额 -->
                <div class="balance-info">
                  <div class="balance-label">当前余额</div>
                  <div class="balance-amount">¥{{ balance || '0.00' }}</div>
                </div>

                <!-- 快捷金额选择 -->
                <div class="amount-section">
                  <h3 class="section-title">选择充值金额</h3>
                  <div class="quick-amounts">
                    <div
                      v-for="amount in quickAmounts"
                      :key="amount"
                      class="amount-item"
                      :class="{ active: selectedAmount === amount }"
                      @click="selectQuickAmount(amount)">
                      <span class="amount-value">¥{{ amount }}</span>
                    </div>
                  </div>
                </div>

                <!-- 自定义金额输入 -->
                <div class="custom-amount-section">
                  <h3 class="section-title">自定义金额</h3>
                  <el-form ref="rechargeFormRef" :model="rechargeForm" :rules="rechargeRules">
                    <el-form-item prop="customAmount">
                      <el-input
                        v-model="rechargeForm.customAmount"
                        placeholder="请输入充值金额"
                        size="large"
                        prefix-icon="Money"
                        clearable
                        @input="handleCustomAmountInput">
                        <template #prepend>¥</template>
                      </el-input>
                    </el-form-item>
                  </el-form>
                  <div class="amount-tips">
                    <span class="tip-item">• 单次充值金额：¥{{ minAmount }} - ¥50,000</span>
                    <span class="tip-item">• 充值金额将实时到账</span>
                  </div>
                </div>

                <!-- 支付方式选择 -->
                <div class="payment-section">
                  <h3 class="section-title">选择支付方式</h3>
                  <div class="payment-methods">
                    <div
                      v-for="method in paymentMethods"
                      :key="method.id"
                      class="payment-item"
                      :class="{ active: selectedPayment === method.id }"
                      @click="selectPayment(method.id)">
                      <div class="payment-icon">
                        <el-icon size="32" :color="getPaymentIconColor(method.id)">
                          <component :is="getPaymentIcon(method.id)" />
                        </el-icon>
                      </div>
                      <div class="payment-info">
                        <div class="payment-name">{{ method.name }}</div>
                        <div class="payment-desc">{{ method.desc }}</div>
                      </div>
                      <div class="payment-radio">
                        <el-radio v-model="selectedPayment" :value="method.id" size="large"></el-radio>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 充值按钮 -->
                <div class="submit-section">
                  <el-button
                    type="primary"
                    size="large"
                    class="recharge-btn"
                    :loading="loading"
                    :disabled="!finalAmount || finalAmount < minAmount"
                    @click="handleRecharge">
                    {{ loading ? '处理中...' : `立即充值 ¥${finalAmount || '0.00'}` }}
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 右侧信息展示 -->
            <div class="info-section">
              <!-- 充值说明 -->
              <div class="info-card">
                <h3 class="card-title">充值说明</h3>
                <div class="info-list">
                  <div class="info-item">
                    <span class="info-icon">💰</span>
                    <span class="info-text">充值金额实时到账，无手续费</span>
                  </div>
                  <div class="info-item">
                    <span class="info-icon">🔒</span>
                    <span class="info-text">支付过程安全加密，保障资金安全</span>
                  </div>
                  <div class="info-item">
                    <span class="info-icon">📱</span>
                    <span class="info-text">支持多种支付方式，操作便捷</span>
                  </div>
                  <div class="info-item">
                    <span class="info-icon">🎁</span>
                    <span class="info-text">充值满额享受专属优惠</span>
                  </div>
                </div>
              </div>

              <!-- 充值记录 -->
              <div class="info-card">
                <h3 class="card-title">最近充值记录</h3>
                <div class="record-list">
                  <div v-if="rechargeRecords.length === 0" class="no-records">暂无充值记录</div>
                  <div v-for="record in rechargeRecords" :key="record.id" class="record-item">
                    <div class="record-info">
                      <div class="record-amount">+ ¥{{ record.change_amount }}</div>
                      <div class="record-time">{{ record.event_time }}</div>
                    </div>
                    <div
                      class="record-status"
                      :class="{ success: record.sync_status === 1, pending: record.sync_status === 0, fail: record.sync_status === 2 }">
                      {{ getStatusText(record.sync_status) }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- 优惠活动 -->
              <!-- <div class="info-card promotion-card">
                <h3 class="card-title">充值优惠</h3>
                <div class="promotion-content">
                  <div class="promotion-item">
                    <div class="promotion-title">首次充值送好礼</div>
                    <div class="promotion-desc">首次充值满100元，送20元优惠券</div>
                  </div>
                  <div class="promotion-item">
                    <div class="promotion-title">充值满额享折扣</div>
                    <div class="promotion-desc">单次充值满500元，享98折优惠</div>
                  </div>
                </div>
              </div> -->
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 微信支付二维码 -->
    <el-dialog v-model="dialogVisible" :modal="true" :close-on-click-modal="false" :width="400">
      <div class="qr-with-text">
        <h2>茶船古道梧州六堡茶官方商城</h2>
        <VueQrcode :value="weixinCodeUrl" :options="{ width: 200 }" tag="img" />
        <p class="text-below">¥ {{ finalAmount }}</p>
      </div>
    </el-dialog>

    <Footer />
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Wallet, ChatDotRound, CreditCard } from '@element-plus/icons-vue'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'
  import VueQrcode from '@chenfengyuan/vue-qrcode'

  const router = useRouter()
  const userStore = useUserStore()
  const rechargeFormRef = ref()
  const loading = ref(false)

  // 微信支付
  const dialogVisible = ref(false)
  const weixinCodeUrl = ref('')

  // 从store获取用户信息
  const userInfo = computed(() => userStore.userInfo)
  const balance = ref(0)

  // 快捷金额选项
  const minAmount = 10
  const quickAmounts = [10, 20, 50, 100, 200, 500, 1000, 2000]

  // 选中的金额和支付方式
  const selectedAmount = ref(null)
  const selectedPayment = ref(1) // 支付方式：1-微信 2-支付宝

  // 表单数据
  const rechargeForm = reactive({
    customAmount: '',
  })

  // 支付方式
  const paymentMethods = [
    {
      id: 1,
      name: '微信支付',
      desc: '微信扫码支付',
    },
    {
      id: 2,
      name: '支付宝',
      desc: '推荐使用，安全便捷',
    },
    // {
    //   id: 'bank',
    //   name: '银行卡',
    //   desc: '支持各大银行卡'
    // }
  ]

  // 获取支付方式图标
  const getPaymentIcon = (paymentId) => {
    const iconMap = {
      alipay: Wallet,
      wechat: ChatDotRound,
      bank: CreditCard,
    }
    return iconMap[paymentId] || CreditCard
  }

  // 获取支付方式图标颜色
  const getPaymentIconColor = (paymentId) => {
    const colorMap = {
      alipay: '#1677ff',
      wechat: '#07c160',
      bank: '#f56c6c',
    }
    return colorMap[paymentId] || '#409eff'
  }

  // 充值记录（模拟数据）
  const rechargeRecords = ref([])

  // 表单验证规则
  const rechargeRules = {
    customAmount: [
      {
        validator: (rule, value, callback) => {
          if (value && (isNaN(value) || parseFloat(value) < minAmount || parseFloat(value) > 50000)) {
            callback(new Error(`充值金额必须在${minAmount}-50000元之间`))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
  }

  // 最终充值金额
  const finalAmount = computed(() => {
    if (rechargeForm.customAmount) {
      const amount = parseFloat(rechargeForm.customAmount)
      return isNaN(amount) ? 0 : amount.toFixed(2)
    }
    return selectedAmount.value ? selectedAmount.value.toFixed(2) : '0.00'
  })

  // 选择快捷金额
  const selectQuickAmount = (amount) => {
    selectedAmount.value = amount
    rechargeForm.customAmount = ''
  }

  // 处理自定义金额输入
  const handleCustomAmountInput = (value) => {
    if (value) {
      selectedAmount.value = null
    }
  }

  // 选择支付方式
  const selectPayment = (paymentId) => {
    selectedPayment.value = paymentId
  }

  // 获取状态文本
  const getStatusText = (status) => {
    const statusMap = {
      1: '成功',
      0: '处理中',
      2: '失败',
    }
    return statusMap[status] || '未知'
  }

  // 处理充值
  const handleRecharge = async () => {
    if (!rechargeFormRef.value) return

    try {
      // 验证表单
      if (rechargeForm.customAmount) {
        const valid = await rechargeFormRef.value.validate()
        if (!valid) return
      }

      const amount = parseFloat(finalAmount.value)
      if (amount < minAmount) {
        ElMessage.warning(`充值金额不能少于${minAmount}元`)
        return
      }

      // 确认充值
      const confirmResult = await ElMessageBox.confirm(`确认充值 ¥${finalAmount.value} 到您的账户吗？`, '确认充值', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info',
      })

      if (confirmResult !== 'confirm') return

      loading.value = true

      // 充值API调用
      const pay_type_desc = paymentMethods.filter((item) => item.id === selectedPayment.value).name
      const saveData = {
        open_user_id: '',
        recharge_amount: finalAmount.value,
        pay_amount: finalAmount.value,
        pay_type: selectedPayment.value,
        pay_type_desc: pay_type_desc,
        remark: '',
      }
      apiUser.AddRechargeOrders(saveData).then((res) => {
        processRecharge(res.data)
      })
    } catch (error) {
      if (error !== 'cancel') {
        console.error('充值失败:', error)
        ElMessage.error('充值失败，请稍后重试')
      }
    } finally {
      loading.value = false
    }
  }

  // 处理充值流程
  const processRecharge = (orderid) => {
    loading.value = true
    apiUser
      .PayRechargeOrders({ id: orderid, good_desc: '充值' })
      .then((res) => {
        loading.value = false
        if (selectedPayment.value === 1) {
          // 微信支付：微信网页支付（NATIVE---商家出示二维码, JSAPI---需要openid）
          const code_url = res.data.code_url // 时效性为2小时
          if (code_url && code_url != '') {
            // 生成支付二维码
            weixinCodeUrl.value = code_url
            dialogVisible.value = true
            // 支付状态：0-待支付 1-支付中 2-支付成功 3-支付失败
            const timer = setInterval(() => {
              apiUser.GetUserRechargeInfo({ id: orderid }).then(async (res) => {
                if (res.data.pay_status === 2) {
                  clearInterval(timer)
                  ElMessage.success('充值成功！')
                  // 重置表单
                  selectedAmount.value = null
                  rechargeForm.customAmount = ''

                  // 可以跳转到充值成功页面或余额页面
                  setTimeout(() => {
                    router.push('/balance')
                  }, 1500)
                }
              })
            }, 2000)
          }
        } else if (selectedPayment.value === 2) {
          // 支付宝支付：微信网页支付（支付结果需要通过异步通知或轮询查询），或者使用JSAPI方式（需要商户授权）
          orderInfo.value.out_trade_no = res.out_trade_no
          // const div = document.createElement('div')
          // div.innerHTML = res.data
          // document.body.appendChild(div)
          // document.forms[0].submit()

          AlipayJSBridge.call(
            'tradePay',
            {
              tradeNO: orderInfo.value.out_trade_no,
              bizContext: res.data, // 后端返回的支付参数
            },
            function (data) {
              if (data.resultCode === '9000') {
                // 支付成功
                ElMessage.success('充值成功！')
                // 重置表单
                selectedAmount.value = null
                rechargeForm.customAmount = ''

                // 可以跳转到充值成功页面或余额页面
                setTimeout(() => {
                  router.push('/balance')
                }, 1500)
              } else if (data.resultCode === '8000' || data.resultCode === '6004') {
                // 正在处理中	支付结果未知（可能已支付成功），需查询订单状态
                ElMessage.success('正在处理中')
                // 重置表单
                selectedAmount.value = null
                rechargeForm.customAmount = ''

                // 可以跳转到充值成功页面或余额页面
                setTimeout(() => {
                  router.push('/balance')
                }, 1500)
              } else if (data.resultCode === '4000') {
                // 订单支付失败	提示用户支付失败，允许重新支付
                ElMessage.error('订单支付失败')
              } else if (data.resultCode === '5000') {
                // 重复请求	用户可能连续点击，检查订单是否已支付
                ElMessage.error('重复请求')
              } else if (data.resultCode === '6001') {
                // 用户中途取消	用户主动取消支付，提示用户
                ElMessage.warning('用户取消支付')
              } else if (data.resultCode === '6002') {
                // 网络连接出错	检查网络后提示用户重试
                ElMessage.warning('网络连接出错')
              } else {
                ElMessage.warning('支付宝支付失败')
              }
            }
          )
        }
      })
      .catch((err) => {
        loading.value = false
      })
  }

  // 分页加载数据
  const fetchData = async () => {
    // 事件类型：1-收入 2-支出 3-充值 4-提现 5-转账(转出) 6-转账(转入)
    apiUser
      .GetBalanceList({
        page: 1,
        limit: 6,
        event_type: 3,
      })
      .then(async (res) => {
        rechargeRecords.value = res.data
      })
  }

  // 查询账户信息
  const loadAccountInfo = () => {
    apiUser.GetAccountInfo().then((res) => {
      if (res.data && res.data.balance) {
        balance.value = res.data.balance
      }
    })
  }

  // 组件挂载时初始化
  onMounted(() => {
    loadAccountInfo()
    fetchData()
  })
</script>

<style scoped>
  .recharge-page {
    min-height: 100vh;
    background: #f8f9fa;
  }

  .recharge-content {
    padding: 40px 0 80px;
    min-height: calc(100vh - 200px);
  }

  .container {
    margin: 0 auto;
    padding: 0 20px;
  }

  .recharge-wrapper {
    margin: 60px auto;
  }

  /* 页面标题 */
  .page-header {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    padding: 60px 0;
    color: white;
    text-align: center;
  }

  .page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 15px 0;
  }

  .page-subtitle {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
  }

  /* 主要内容区域 */
  .recharge-main {
    display: grid;
    grid-template-columns: 1fr 350px;
    gap: 30px;
  }

  /* 左侧表单区域 */
  .recharge-form-section {
    background: white;
    border-radius: 12px;
    overflow: hidden;
  }

  .form-card {
    padding: 30px;
  }

  /* 余额信息 */
  .balance-info {
    background: linear-gradient(135deg, #1c705e 0%, #2d8a6e 100%);
    color: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 30px;
    text-align: center;
  }

  .balance-label {
    font-size: 14px;
    opacity: 0.9;
    margin-bottom: 8px;
  }

  .balance-amount {
    font-size: 28px;
    font-weight: 600;
  }

  /* 金额选择区域 */
  .amount-section {
    margin-bottom: 30px;
  }

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
  }

  .quick-amounts {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
  }

  .amount-item {
    padding: 16px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
    background: white;
  }

  .amount-item:hover {
    border-color: #1c705e;
    background: #f0f8f5;
  }

  .amount-item.active {
    border-color: #1c705e;
    background: #1c705e;
    color: white;
  }

  .amount-value {
    font-size: 16px;
    font-weight: 600;
  }

  /* 自定义金额区域 */
  .custom-amount-section {
    margin-bottom: 30px;
  }

  .amount-tips {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-top: 8px;
  }

  .tip-item {
    font-size: 12px;
    color: #999;
  }

  /* 支付方式区域 */
  .payment-section {
    margin-bottom: 30px;
  }

  .payment-methods {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .payment-item {
    display: flex;
    align-items: center;
    padding: 16px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
  }

  .payment-item:hover {
    border-color: #1c705e;
    background: #f0f8f5;
  }

  .payment-item.active {
    border-color: #1c705e;
    background: #f0f8f5;
  }

  .payment-icon {
    width: 40px;
    height: 40px;
    margin-right: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .payment-info {
    flex: 1;
  }

  .payment-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
  }

  .payment-desc {
    font-size: 14px;
    color: #666;
  }

  /* 提交按钮 */
  .submit-section {
    margin-top: 30px;
  }

  .recharge-btn {
    width: 100%;
    height: 50px;
    font-size: 16px;
    font-weight: 600;
    background: #1c705e;
    border-color: #1c705e;
  }

  .recharge-btn:hover {
    background: #2d8a6e;
    border-color: #2d8a6e;
  }

  .recharge-btn:disabled {
    background: #ccc;
    border-color: #ccc;
  }

  /* 右侧信息区域 */
  .info-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .info-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
  }

  .card-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
  }

  /* 充值说明 */
  .info-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .info-item {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .info-icon {
    font-size: 20px;
    flex-shrink: 0;
  }

  .info-text {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }

  /* 充值记录 */
  .record-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .no-records {
    text-align: center;
    color: #999;
    padding: 20px;
    font-size: 14px;
  }

  .record-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .record-item:last-child {
    border-bottom: none;
  }

  .record-amount {
    font-size: 16px;
    font-weight: 600;
    color: #1c705e;
  }

  .record-time {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }

  .record-status {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 4px;
  }

  .record-status.success {
    background: #e8f5e8;
    color: #4caf50;
  }

  .record-status.pending {
    background: #fff3cd;
    color: #856404;
  }

  .record-status.failed {
    background: #f8d7da;
    color: #721c24;
  }

  /* 优惠活动 */
  .promotion-card {
    background: linear-gradient(135deg, #fff7e6 0%, #fff2d9 100%);
    border: 1px solid #ffd591;
  }

  .promotion-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .promotion-item {
    padding: 12px;
    background: white;
    border-radius: 6px;
    border-left: 4px solid #ff9500;
  }

  .promotion-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
  }

  .promotion-desc {
    font-size: 12px;
    color: #666;
  }

  .qr-with-text {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .text-below {
    color: #ff0000;
    font-size: 28px;
    font-weight: bold;
    margin: 5px;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .recharge-main {
      grid-template-columns: 1fr;
      gap: 20px;
    }

    .info-section {
      order: -1;
    }

    .quick-amounts {
      grid-template-columns: repeat(2, 1fr);
    }

    .page-title {
      font-size: 24px;
    }

    .form-card {
      padding: 20px;
    }
  }

  @media (max-width: 480px) {
    .container {
      padding: 0 15px;
    }

    .recharge-content {
      padding: 20px 0 60px;
    }

    .quick-amounts {
      grid-template-columns: 1fr;
    }

    .payment-item {
      padding: 12px;
    }

    .info-card {
      padding: 16px;
    }
  }
</style>
